<template>
    <div class="button-container">
      <el-button type="text" class="custom-button" @click="open">点击登录</el-button>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  export default {
    data() {
        return {
            listData: [],
            filteredList: []
        };
    },
    mounted() {
        this.fetchDataList();
    },
    methods: {
        async fetchDataList() {
            try {
                const response = await axios.get('http://websocket.1uu.pw/user/page?pageSize=999');
                this.listData = response.data.data.records;
                console.log(response.data.data.records);
                this.filteredList = this.listData;
            } catch (error) {
                console.error('获取列表数据失败:', error);
            }
        },
        open() {
            this.$prompt('请输入姓名', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(({ value }) => {
                const user = this.validateLogin(value); // 获取用户对象
                if (user) {
                    this.$message({
                        type: 'success',
                        message: '登录成功！'
                    });
                    this.getId(user.id); // 传递用户 ID 进行跳转
                } else {
                    this.$message({
                        type: 'error',
                        message: '姓名不存在，请检查输入！'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });
            });
        },
        validateLogin(name) { 
            for (let i = 0; i < this.listData.length; i++) {
                if (this.listData[i].name === name) {
                    return this.listData[i]; // 返回用户对象（包含 ID）
                }
            }
            return null;
        },
        getId(userId) {
            // 跳转到 /wechat 页面，并通过 query 或 params 传递用户 ID
            this.$router.push({
                path: '/wechat',
                query: { id: userId } // 或使用 params: { id: userId }，需根据路由配置
            });
        //    获取当前登录用户的姓名（listData中）
        const user=this.listData.find(item =>item.id ===userId);
        if (user) {
            // 提交mutation存储用户信息到vuex
            this.$store.commit('updateCurrentUser',user)
            
        }
            
        }
    }
  };
  </script>
  
  <style scoped>
  .button-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
  }
  
  .custom-button {
    background-color: #409eff;
    color: white;
    padding: 12px 24px;
    border-radius: 4px;
    text-transform: uppercase;
    transition: background-color 0.3s ease;
  }
  
  .custom-button:hover {
    background-color: #3a8ee6;
  }
  </style>